
#from typing import Optional
#from uuid import UUID
import asyncio
#from voluptuous.validators import truth
from homeassistant.const import (EVENT_HOMEASSISTANT_START,
                                 EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED)

from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
#import homeassistant.helpers.config_validation as cv
#import voluptuous as vol
from  .VioceApp import VioceApp
import logging
#import os
_LOGGER = logging.getLogger(__name__)

from .const import DOMAIN
'''CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Optional(CONF_USERNAME): cv.string,
        vol.Optional(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_NAME,default='voice'): cv.string,
        vol.Optional(CONF_SELECT,default= True): cv.boolean,
        vol.Optional(CONF_DEVICES,default=[]):
            vol.All(cv.ensure_list,[{
                vol.Required(ATTR_ENTITY_ID): cv.string,
                vol.Required(ATTR_FRIENDLY_NAME): cv.string
        }]),
    }, extra=vol.ALLOW_EXTRA),
}, extra=vol.ALLOW_EXTRA)'''


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}
    HUB_UID = entry.data['uid']
   
    
    async def on_state_changed(event):
       await hass.data[DOMAIN][HUB_UID].ha_state_changed(event)

    
    async def start_app():
        if HUB_UID not in hass.data[DOMAIN]:
            hass.data[DOMAIN][HUB_UID]   =  VioceApp(hass,entry)
        elif hass.data[DOMAIN][HUB_UID] == None:
            hass.data[DOMAIN][HUB_UID]   =  VioceApp(hass,entry)

        if hass.data[DOMAIN][HUB_UID].flag:
            return
        await hass.data[DOMAIN][HUB_UID].start()
        hass.data[DOMAIN]['started'] = True
        hass.bus.async_listen(EVENT_STATE_CHANGED, on_state_changed)

    if 'started' in hass.data[DOMAIN]:
        await start_app()

    

    async def async_stop_app(e):
        await hass.data[DOMAIN][HUB_UID].stop()

    async def ha_start(e):
        await start_app()
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_app)

    hass.bus.async_listen(EVENT_HOMEASSISTANT_START, ha_start)


    if (HUB_UID not in hass.data[DOMAIN]):
        await asyncio.sleep(2)
        if 'started' not  in hass.data[DOMAIN]:
            await start_app()

    return True
   

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
    HUB_UID = entry.data['uid']
    await hass.data[DOMAIN][HUB_UID].stop()
    _LOGGER.error('RELOAD')
    #hass.data[DOMAIN][entry.data['uid']].client= None
    hass.data[DOMAIN][entry.data['uid']] = None

    return True

